package com.yubiaoqing;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.util.EnvironmentUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author hehb
 * @date 2020/04/04 04:22
 */
public class Tools {

    public static void runBuild(Project project) {

        MyToolWindow.getInstance().activate(project);
        // 异步执行命令，防止卡顿
        ApplicationManager.getApplication().executeOnPooledThread(
                new AsyncBuilder(project));

    }

    private static class AsyncBuilder implements Runnable {

        private final Project project;
        private static String[] cmds = new String[]{
                "/bin/bash",
                "-c",
                "flutter pub run build_runner build"};

        private AsyncBuilder(Project project) {
            this.project = project;
        }

        @Override
        public void run() {
            try {
                ProcessBuilder builder = new ProcessBuilder(cmds)
                        .directory(new File(project.getBasePath())).redirectErrorStream(true);
                //TODO 注意了不可以使用System.getenv(),是取不到自己设置的环境变量的，使用EnvironmentUtil代替
                builder.environment().put("PATH", EnvironmentUtil.getValue("PATH"));
                //Messages.showMessageDialog(project, System.getenv().toString(), "", null);
                Process process = builder.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                    MyToolWindow.getInstance().println(line);
                    // 等待，不加这句代码process会永远等待，不会结束
                    process.waitFor();
                }
                // 关闭process
                reader.close();
                process.destroy();
                // 刷新目录结构
                ProjectUtil.guessProjectDir(project).refresh(true, true);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
